using SplineMesh;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyCar : MonoBehaviour
{
    [SerializeField] private GameObject[] EnemyCars;
    private Spline _splineLoad;
    private float _speed = 4;
    private float _curLength = 0;
    private float _totalLength = 0;

    public void Init(Spline sp, float speed)
    {
        _splineLoad = sp;
        _speed = speed;
        _totalLength = _splineLoad.Length;
        _curLength = 0;

        CurveSample sample = _splineLoad.GetSampleAtDistance(_curLength);
        transform.position = sample.location;
        transform.rotation = sample.Rotation;
        EventMgr.EvtReleaseAllEnemy.RemoveListener(Release);
        EventMgr.EvtReleaseAllEnemy.AddListener(Release);
    }

    private void Update()
    {
        if (!gameObject.activeSelf) {
            return;
        }

        if (LevelMgr.Instance.State == GameState.Running || LevelMgr.Instance.State == GameState.Over || LevelMgr.Instance.State == GameState.Stop) {
            _curLength += _speed * Time.deltaTime;
            if (_curLength >= _totalLength) {
                _curLength = 0;
                Release();
                return;
            }
            CurveSample sample = _splineLoad.GetSampleAtDistance(_curLength);
            transform.position = sample.location;
            transform.rotation = sample.Rotation;
        }
    }

    private void Release() {
        EnemyPool.Instance.Pool.Release(gameObject);
        gameObject.SetActive(false);
        EventMgr.EvtReleaseAllEnemy.RemoveListener(Release);
    }
}
